namespace CloudNinja.Metering.Common.Configuration
{
    using System;
    using System.Configuration;

    using Microsoft.Practices.Unity;

    public abstract class ProviderElement : ConfigurationElement, ITypeRegistration
    {
        [ConfigurationProperty("Type", IsRequired = true)]
        public string Type
        {
            get
            {
                return (string)this["Type"];
            }

            set
            {
                this["Type"] = value;
            }
        }

        [ConfigurationProperty("CollectInterval", IsRequired = false)]
        public TimeSpan CollectInterval
        {
            get
            {
                var currentValue = (TimeSpan)this["CollectInterval"];

                if (currentValue != TimeSpan.Zero)
                {
                    return currentValue;
                }

                var configuration = this.CurrentConfiguration;

                var meteringConfig = configuration.Sections["MeteringConfiguration"] as MeteringSection;

                if (meteringConfig == null)
                {
                    throw new ConfigurationErrorsException("Metering configuration is not named as MeteringConfiguration or no Metering configuration is found.");
                }

                var defaultValue = meteringConfig.ProviderSettings.DefaultCollectionInterval;

                return defaultValue;
            }

            set
            {
                this["CollectInterval"] = value;
            }
        }

        public abstract void RegisterType(IUnityContainer container, MeteringSection meteringConfiguration);

        //protected override bool OnDeserializeUnrecognizedElement(string elementName, System.Xml.XmlReader reader)
        //{
        //    return elementName.Equals("IISLogMeteringProviderSettings") || base.OnDeserializeUnrecognizedElement(elementName, reader);
        //}
    }
}